<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <text class="header-title">我的订单</text>
      <view class="header-actions">
        <text class="filter-btn" @click="showFilter = true">筛选</text>
      </view>
    </view>

    <!-- 状态筛选 -->
    <scroll-view class="status-scroll" scroll-x="true">
      <view 
        v-for="status in statusOptions" 
        :key="status.value"
        :class="['status-item', { active: activeStatus === status.value }]"
        @click="selectStatus(status.value)"
      >
        <text>{{ status.label }}</text>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <view class="orders-list">
      <view 
        v-for="order in filteredOrders" 
        :key="order.id"
        class="order-card"
        @click="viewOrderDetail(order)"
      >
        <view class="order-header">
          <text class="order-number">订单号: {{ order.order_number }}</text>
          <view :class="['order-status', getStatusClass(order.status)]">
            <text>{{ getStatusText(order.status) }}</text>
          </view>
        </view>

        <view class="order-info">
          <text class="info-item">桌号: {{ order.table_number }}</text>
          <text class="info-item">时间: {{ formatTime(order.created_at) }}</text>
          <text class="info-item" v-if="order.customer_name">姓名: {{ order.customer_name }}</text>
        </view>

        <view class="order-items">
          <text class="items-label">菜品:</text>
          <view class="items-list">
            <text 
              v-for="(item, index) in order.items.slice(0, 3)" 
              :key="index"
              class="item-name"
            >
              {{ item.name }} ×{{ item.quantity }}
            </text>
            <text v-if="order.items.length > 3" class="more-items">...等{{ order.items.length }}件商品</text>
          </view>
        </view>

        <view class="order-footer">
          <text class="total-amount">总计: ${{ order.grand_total }}</text>
          <view class="order-actions">
            <text 
              v-if="order.status === 'pending'" 
              class="action-btn cancel"
              @click.stop="cancelOrder(order)"
            >
              取消订单
            </text>
            <text 
              v-if="order.status === 'ready'" 
              class="action-btn complete"
              @click.stop="completeOrder(order)"
            >
              确认完成
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="filteredOrders.length === 0" class="empty-state">
      <text class="empty-icon">📦</text>
      <text class="empty-text">暂无订单</text>
      <text class="empty-desc">去点一些美食吧</text>
      <text class="browse-btn" @click="navigateToMenu">浏览菜单</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>

    <!-- 筛选弹窗 -->
    <uni-popup ref="filterPopup" type="bottom">
      <view class="filter-popup">
        <view class="popup-header">
          <text class="popup-title">筛选订单</text>
          <text class="popup-close" @click="showFilter = false">×</text>
        </view>
        <view class="filter-options">
          <view class="filter-group">
            <text class="filter-label">时间范围</text>
            <view class="filter-buttons">
              <text 
                v-for="time in timeFilters" 
                :key="time.value"
                :class="['filter-btn', { active: filters.time_range === time.value }]"
                @click="toggleTimeFilter(time.value)"
              >
                {{ time.label }}
              </text>
            </view>
          </view>
          <view class="filter-group">
            <text class="filter-label">排序方式</text>
            <view class="filter-buttons">
              <text 
                v-for="sort in sortOptions" 
                :key="sort.value"
                :class="['filter-btn', { active: filters.sort_by === sort.value }]"
                @click="toggleSortFilter(sort.value)"
              >
                {{ sort.label }}
              </text>
            </view>
          </view>
        </view>
        <view class="popup-actions">
          <text class="action-btn reset" @click="resetFilters">重置</text>
          <text class="action-btn apply" @click="applyFilters">应用</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orders: [],
      loading: false,
      activeStatus: 'all',
      showFilter: false,
      filters: {
        time_range: null,
        sort_by: 'newest'
      },
      statusOptions: [
        { value: 'all', label: '全部' },
        { value: 'pending', label: '待处理' },
        { value: 'preparing', label: '制作中' },
        { value: 'ready', label: '已就绪' },
        { value: 'completed', label: '已完成' },
        { value: 'cancelled', label: '已取消' }
      ],
      timeFilters: [
        { value: 'today', label: '今天' },
        { value: 'week', label: '本周' },
        { value: 'month', label: '本月' },
        { value: 'all', label: '全部时间' }
      ],
      sortOptions: [
        { value: 'newest', label: '最新优先' },
        { value: 'oldest', label: '最旧优先' },
        { value: 'price_high', label: '价格从高到低' },
        { value: 'price_low', label: '价格从低到高' }
      ]
    }
  },

  computed: {
    filteredOrders() {
      let filtered = this.orders

      // 状态筛选
      if (this.activeStatus !== 'all') {
        filtered = filtered.filter(order => order.status === this.activeStatus)
      }

      // 时间筛选
      if (this.filters.time_range) {
        const now = new Date()
        switch (this.filters.time_range) {
          case 'today':
            const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
            filtered = filtered.filter(order => new Date(order.created_at) >= today)
            break
          case 'week':
            const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
            filtered = filtered.filter(order => new Date(order.created_at) >= weekAgo)
            break
          case 'month':
            const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate())
            filtered = filtered.filter(order => new Date(order.created_at) >= monthAgo)
            break
        }
      }

      // 排序
      switch (this.filters.sort_by) {
        case 'newest':
          filtered.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
          break
        case 'oldest':
          filtered.sort((a, b) => new Date(a.created_at) - new Date(b.created_at))
          break
        case 'price_high':
          filtered.sort((a, b) => b.grand_total - a.grand_total)
          break
        case 'price_low':
          filtered.sort((a, b) => a.grand_total - b.grand_total)
          break
      }

      return filtered
    }
  },

  onLoad() {
    this.loadOrders()
  },

  onShow() {
    // 页面显示时刷新订单列表
    this.loadOrders()
  },

  methods: {
    async loadOrders() {
      this.loading = true
      try {
        const res = await uni.request({
          url: 'http://localhost/api/orders',
          method: 'GET'
        })
        
        if (res.data.success) {
          this.orders = res.data.data
        }
      } catch (error) {
        console.error('加载订单失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    selectStatus(status) {
      this.activeStatus = status
    },

    viewOrderDetail(order) {
      uni.navigateTo({
        url: `/pages/orders/detail?id=${order.id}`
      })
    },

    async cancelOrder(order) {
      uni.showModal({
        title: '确认取消',
        content: '确定要取消这个订单吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const result = await uni.request({
                url: 'http://localhost/api/orders',
                method: 'PUT',
                data: {
                  id: order.id,
                  status: 'cancelled'
                },
                header: {
                  'Content-Type': 'application/json'
                }
              })

              if (result.data.success) {
                uni.showToast({
                  title: '订单已取消',
                  icon: 'success'
                })
                this.loadOrders() // 刷新列表
              }
            } catch (error) {
              console.error('取消订单失败:', error)
              uni.showToast({
                title: '取消失败',
                icon: 'none'
              })
            }
          }
        }
      })
    },

    async completeOrder(order) {
      try {
        const result = await uni.request({
          url: 'http://localhost/api/orders',
          method: 'PUT',
          data: {
            id: order.id,
            status: 'completed'
          },
          header: {
            'Content-Type': 'application/json'
          }
        })

        if (result.data.success) {
          uni.showToast({
            title: '订单已完成',
            icon: 'success'
          })
          this.loadOrders() // 刷新列表
        }
      } catch (error) {
        console.error('完成订单失败:', error)
        uni.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    },

    getStatusText(status) {
      const statusMap = {
        pending: '待处理',
        preparing: '制作中',
        ready: '已就绪',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    },

    getStatusClass(status) {
      return `status-${status}`
    },

    formatTime(time) {
      const date = new Date(time)
      return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    navigateToMenu() {
      uni.switchTab({
        url: '/pages/menu/menu'
      })
    },

    toggleTimeFilter(value) {
      this.filters.time_range = this.filters.time_range === value ? null : value
    },

    toggleSortFilter(value) {
      this.filters.sort_by = value
    },

    applyFilters() {
      this.showFilter = false
    },

    resetFilters() {
      this.filters = {
        time_range: null,
        sort_by: 'newest'
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 0;
  background: #f8f8f8;
  min-height: 100vh;
}

.header {
  background: white;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.filter-btn {
  color: #ff6b6b;
  font-size: 28rpx;
}

.status-scroll {
  background: white;
  padding: 20rpx 30rpx;
  white-space: nowrap;
  border-bottom: 1rpx solid #eee;
}

.status-item {
  display: inline-block;
  padding: 16rpx 32rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background: #f8f8f8;
  color: #666;
  font-size: 28rpx;
}

.status-item.active {
  background: #ff6b6b;
  color: white;
}

.orders-list {
  padding: 20rpx;
}

.order-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-number {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.order-status {
  padding: 8rpx 16rpx;
  border-radius: 15rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background: #ffeaa7;
  color: #d35400;
}

.status-preparing {
  background: #74b9ff;
  color: #0984e3;
}

.status-ready {
  background: #55efc4;
  color: #00b894;
}

.status-completed {
  background: #b2bec3;
  color: #636e72;
}

.status-cancelled {
  background: #fab1a0;
  color: #e17055;
}

.order-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.info-item {
  font-size: 26rpx;
  color: #666;
  background: #f8f8f8;
  padding: 8rpx 16rpx;
  border-radius: 15rpx;
}

.order-items {
  margin-bottom: 20rpx;
}

.items-label {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.items-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.item-name {
  font-size: 26rpx;
  color: #666;
  background: #f8f8f8;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.more-items {
  font-size: 24rpx;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.total-amount {
  font-size: 32rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.order-actions {
  display: flex;
  gap: 15rpx;
}

.action-btn {
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
}

.action-btn.cancel {
  background: #ffeaa7;
  color: #d35400;
}

.action-btn.complete {
  background: #55efc4;
  color: #00b894;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 36rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 40rpx;
}

.browse-btn {
  background: #ff6b6b;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 30rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.loading {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #ff6b6b;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.filter-popup {
  background: white;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.filter-group {
  margin-bottom: 40rpx;
}

.filter-label {
  display: block;
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.filter-btn {
  padding: 16rpx 32rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 25rpx;
  font-size: 26rpx;
  color: #666;
}

.filter-btn.active {
  border-color: #ff6b6b;
  background: #ff6b6b;
  color: white;
}

.popup-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 40rpx;
}

.action-btn {
  flex: 1;
  text-align: center;
  padding: 25rpx;
  border-radius: 25rpx;
  font-size: 30rpx;
  font-weight: 500;
}

.action-btn.reset {
  background: #f8f8f8;
  color: #666;
}

.action-btn.apply {
  background: #ff6b6b;
  color: white;
}
</style>